import threading
import logging
import logging.config

from app import app
from utils.dbm import DBManager
from utils.mssqlm import MSSqlManager
from utils.wxapi import WxClient
from utils.configReader import myconfigReader

import time

class WX_MSSQL_Push:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.ms_conn = MSSqlManager()
        pass

    def push_shouhou_to_wx(self):
        self.logger.info("检查售后信息...")
        rows = self.ms_conn.selectShouhou()
        has_new = False
        for row in rows:
            self.logger.info("推送一条售后：%s" %(row))
            one_row_status = self.push_one_row_shouhou(row)
            self.logTSInfo(row, one_row_status)
            has_new = True
        if has_new:
            self.ms_conn.updateShouhou();
        else:
            self.logger.info("没有新的售后信息.")

    def push_anzhuang_to_wx(self):
        ms_conn = self.ms_conn
        # 检查送货信息
        self.logger.info("检查送货信息...")
        rows = ms_conn.selectAZ()
        has_new = False
        for row in rows:
            self.logger.info("推送一条送货信息：%s" % (row))
            one_row_status = self.push_one_row_az(row)
            self.logTSInfo(row, one_row_status)
            has_new = True
        if has_new:
            ms_conn.updateAZ()
        else:
            self.logger.info("没有送货信息.")

    def push_jindu_to_wx(self):
        ms_conn = self.ms_conn
        # 检查送货信息
        self.logger.info("检查进度信息")
        rows = ms_conn.selectJD()
        has_new = False
        for row in rows:
            self.logger.info("推送一条进度：%s" % (row))
            one_row_status = self.push_one_row_jd(row)
            self.logTSInfo(row, one_row_status)
            has_new = True
        if has_new:
            ms_conn.updateJD()
        else:
            self.logger.info("没有进度信息")

    def push_YXKH_to_wx(self):
        ms_conn = self.ms_conn
        # 检查意向客户信息
        self.logger.info("检查新建的意向客户")
        rows = ms_conn.selectYXKH()
        has_new = False
        for row in rows:
            self.logger.info("推送一条意向客户：%s" % (row))
            one_row_status = self.push_one_row_YXKH(row)
            self.logTSInfo(row, one_row_status)
            has_new = True
        if has_new:
            ms_conn.updateYXKH()
        else:
            self.logger.info("没有新建意向客户")

    # 推送一条意向客户
    def push_one_row_YXKH(self, row):
        id = row[0]
        retail = row[1]
        name = row[2]
        url = "http://fuwu.yimujiaju.cn/admin/showyx.asp?id=%s" % id
        msg = "[%s]的[%s] 新建了一条意向客户信息，详情: %s " % (retail, name, url)
        wx_client = WxClient()
        status = wx_client.addNewService(toUser=myconfigReader.feedback_add_receiver, content=msg, agentid=5)
        return status

    # 推送一条进度信息
    def push_one_row_jd(self, row):
        id = row[0]
        name = row[1]
        tele = row[2]
        mobile = row[3]
        url = "http://fuwu.yimujiaju.cn/admin/songhuo.asp?moduleid=%s" % id
        msg = "收到一条进度信息\n姓名：%s\n电话：%s\n手机号：%s\n详情：%s" % (name, tele, mobile, url)
        print(msg)
        wx_client = WxClient()
        status = wx_client.addNewService(toUser=myconfigReader.feedback_add_receiver,
                                         toParty=myconfigReader.feedback_shouhou_receiver, content=msg)
        return status

    # 推送一条安装信息
    def push_one_row_az(self, row):
        id = row[0]
        name = row[1]
        tele = row[2]
        mobile = row[3]
        url = "http://fuwu.yimujiaju.cn/admin/showsonghuo.asp?id=%s" %id
        msg = "收到一条安装信息\n姓名：%s\n电话：%s\n手机号：%s\n详情：%s" %(name, tele, mobile, url)
        print(msg)
        wx_client = WxClient()
        status = wx_client.addNewService(toUser=myconfigReader.feedback_add_receiver,toParty=myconfigReader.feedback_anzhuang_receiver,content=msg)
        return status

    def push_one_row_shouhou(self, row):
        name = row[2]
        phone = row[3]
        feedback_url = "http://fuwu.yimujiaju.cn/admin/showshouhou.asp?id=%s" %row[0]
        msg = "收到一条客户反馈\n姓名：%s\n手机号：%s\n链接：%s" % (name, phone, feedback_url)
        wx_client = WxClient()
        status = wx_client.addNewService(toUser=myconfigReader.feedback_add_receiver,toParty=myconfigReader.feedback_shouhou_receiver,content=msg)
        return status

    def upadteLastId(self,id):
        mydb = DBManager()
        mydb.update_last_id(id)
        mydb.close()

    def getLastId(self):
        mydb = DBManager()
        id = mydb.get_last_id_in_PGD()
        mydb.close()
        return id

    def logTSInfo(self, row, status):
        if status:
            self.logger.info("推送成功")
        else:
            self.logger.error("推送失败：%s" % (row))

def check_mssql_PGD():
    wx_ms = WX_MSSQL_Push()
    while True:
        wx_ms.push_shouhou_to_wx()
        wx_ms.push_anzhuang_to_wx()
        wx_ms.push_jindu_to_wx()
        wx_ms.push_YXKH_to_wx()
        # print("sleep ...")
        time.sleep(1)

if __name__ == "__main__":
    # logging.config.fileConfig(app.root_path + '/log.conf')
    # t = threading.Thread(target=check_mssql_PGD, name='checkMSSQL')
    # t.start()

    wx_ms = WX_MSSQL_Push()
    wx_ms.push_YXKH_to_wx()
